import {
	defineStore
} from 'pinia';
import {
	wxLogin,
	userLogin,
	getUserInfo,
	refreshUserToken
} from '@/api/permission.js'
import {
	setToken,
	removeToken,
	getRefreshToken,
	setRefreshToken,
	removeRefreshToken,
	setExpiresTime,
	removeExpiresTime,
} from '@/utils/token.js'

const initUserInfo = {
	id: undefined,
};

export const useUserStore = defineStore('user', {
	state: () => ({
		userInfo: {
			...initUserInfo
		},
	}),
	getters: {
		userId: (state) => {
			return state.userInfo.id
		},
		newReceiveStatus: (state) => {
			return state.userInfo.newReceiveStatus
		}
	},
	actions: {
		wxLogin() {
			return new Promise((resolve,reject)=>{
				uni.login({
					success: ({
						code
					}) => {
						wxLogin({
							code
						}).then(res => {
							this.userInfo.id = res.id
							this.getUserInfo()
							resolve(res)
						}).catch((error) => {
							setTimeout(async () => {
								await this.wxLogin()
							}, 1000)
							reject(error)
						})
					},
					fail: (error) => {
						setTimeout(() => {}, 1000)
						reject(error)
					}
				})
			})
		},
		async login(userInfo) {
			const res = await userLogin(userInfo);
			setToken(res.accessToken)
			setRefreshToken(res.refreshToken);
			setExpiresTime(res.expiresTime);
		},
		async getUserInfo() {
			const res = await getUserInfo({
				wxUserId: this.userId
			});
			this.userInfo = res
		},
		refreshToken() {
			return refreshUserToken({
				refreshToken: getRefreshToken()
			}).then((res) => {
				setToken(res.accessToken)
				setRefreshToken(res.refreshToken);
				setExpiresTime(res.expiresTime);
			})
		},
		logout() {
			removeToken()
			removeRefreshToken()
			removeExpiresTime()
			this.userInfo = {
				...initUserInfo
			};
		},
	},
});